#include"LSYEasyBody.h"
#include"LSYEasyWorld.h"
#include"GLES-Render.h"
#include"Tool.h"

#define RELEASE()  \
REALSE_NULL(bd)  \
REALSE_NULL(shape)  \
REALSE_NULL(fd)

b2Body * LSYEasyBody::createBox(const b2Vec2 & pos, const b2Vec2 & size,b2BodyType type)
{
	b2BodyDef* bd = new b2BodyDef;
	bd->type = type;
	bd->position = b2Vec2(pos.x*PTM_RADIO, pos.y*PTM_RADIO);

	b2PolygonShape* shape = new b2PolygonShape;
	shape->SetAsBox(size.x*PTM_RADIO, size.y*PTM_RADIO);

	b2FixtureDef* fd = new b2FixtureDef;
	fd->shape = shape;

	b2Body* body = LSYEasyWorld::pWorld->CreateBody(bd);
	body->CreateFixture(fd);

	RELEASE();
	return body;
}

b2Body * LSYEasyBody::createCircle(const b2Vec2 & pos, const float & radius, b2BodyType type)
{
	b2BodyDef* bd = new b2BodyDef;
	bd->type = type;
	bd->position = b2Vec2(pos.x*LSYEasyWorld::PTOM, pos.y*LSYEasyWorld::PTOM);

	b2CircleShape* shape = new b2CircleShape;
	shape->m_radius = radius * LSYEasyWorld::PTOM;

	b2FixtureDef* fd = new b2FixtureDef;
	fd->shape = shape;

	b2Body* body = LSYEasyWorld::pWorld->CreateBody(bd);
	body->CreateFixture(fd);
	
	RELEASE();
	return body;
}

void LSYEasyBody::createRectangle(const b2Vec2 & pos, const float & width, const float & height)
{
	b2Vec2 rpos = b2Vec2(pos.x*LSYEasyWorld::PTOM, pos.y*LSYEasyWorld::PTOM);
	float rwidth = width * LSYEasyWorld::PTOM;
	float rheight = height * LSYEasyWorld::PTOM;
	b2BodyDef* bd = new b2BodyDef;
	bd->type = b2BodyType::b2_staticBody;
	bd->position = rpos;
	b2Body* body = LSYEasyWorld::pWorld->CreateBody(bd);
	
	b2EdgeShape* edge = new b2EdgeShape;
	edge->Set(rpos, b2Vec2(rpos.x, rpos.y + rheight));
	body->CreateFixture(edge, 1);
	edge->Set(rpos, b2Vec2(rpos.x + rwidth, rpos.y));
	body->CreateFixture(edge, 1);
	edge->Set(b2Vec2(rpos.x, rpos.y + rheight), b2Vec2(rpos.x + rwidth, rpos.y + rheight));
	body->CreateFixture(edge, 1);
	edge->Set(b2Vec2(rpos.x + rwidth, rpos.y), b2Vec2(rpos.x + rwidth, rpos.y + rheight));
	body->CreateFixture(edge, 1);

	REALSE_NULL(bd);
	REALSE_NULL(edge);
}

void LSYEasyBody::fixBodyAt(b2Body * body, const b2Vec2 & pos)
{
	b2BodyDef* def = new b2BodyDef;
	def->type = b2BodyType::b2_staticBody;
	def->position = b2Vec2(pos.x*PTM_RADIO, pos.y*PTM_RADIO);
	auto bodya =LSYEasyWorld::pWorld->CreateBody(def);
	b2RopeJointDef* rd = new b2RopeJointDef;
	rd->bodyA = bodya;
	rd->bodyB = body;
	rd->localAnchorA = b2Vec2(0, 0);
	rd->localAnchorB = b2Vec2(0, 0);
	LSYEasyWorld::pWorld->CreateJoint(rd);
	REALSE_NULL(def);
	REALSE_NULL(rd);
}
